package com.qianxx.component.activity.recycleview.pull_recyclerview;

import android.animation.ValueAnimator;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.TextView;

import com.qianxx.component.R;
import com.qianxx.viewlibrary.recyclerview.pull.AbRefreshHeadView;
import com.qianxx.viewlibrary.recyclerview.refreshview.DisplayUtil;

/**
 * 下拉刷新视图
 */
public class RefreshHeadView extends AbRefreshHeadView {
    private ImageView mIvAnim;
    private TextView mTvTip;

    public RefreshHeadView(Context context) {
        super(context);
    }

    @Override
    protected View onCreateView(Context context) {
        return LayoutInflater.from(context).inflate(R.layout.view_refresh_head, null);
    }

    @Override
    protected int onCreateRefreshLimitHeight() {
        return DisplayUtil.dp2px(getContext(), 40);
    }

    @Override
    protected void initView() {
        mIvAnim = (ImageView) findViewFromId(R.id.iv_ball);
        mTvTip = (TextView) findViewFromId(R.id.tv_hint);
    }

    private void rotationAnimator(float rotation) {
        ValueAnimator animator = ValueAnimator.ofFloat(mIvAnim.getRotation(), rotation);
        animator.setDuration(200).start();
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                mIvAnim.setRotation((Float) animation.getAnimatedValue());
            }
        });
        animator.start();
    }

    //下拉刷新
    @Override
    protected void onPullingDown() {
        mIvAnim.setVisibility(VISIBLE);
        mTvTip.setVisibility(INVISIBLE);
        rotationAnimator(0f);
    }

    //释放立即刷新
    @Override
    protected void onReleaseState() {
        mIvAnim.setVisibility(VISIBLE);
        mTvTip.setVisibility(INVISIBLE);
        rotationAnimator(180f);
    }

    //正在刷新
    @Override
    protected void onRefreshing() {
        mTvTip.setVisibility(INVISIBLE);
        mIvAnim.startAnimation(AnimationUtils.loadAnimation(mContext, R.anim.rotate));
    }

    //刷新成功
    @Override
    protected void onResultSuccess() {
        mIvAnim.clearAnimation();
        mTvTip.setVisibility(VISIBLE);
        mIvAnim.setVisibility(INVISIBLE);
    }

    //刷新失败
    @Override
    protected void onResultFail() {
        mIvAnim.clearAnimation();
        mTvTip.setVisibility(VISIBLE);
        mIvAnim.setVisibility(INVISIBLE);
    }
}
